<?php
/**
 * ArticleController.php
 *
 * 日志控制器.
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://momoger.com/license
 *
 * @category	Home
 * @package		Home_Controller
 * @author 		Leo
 * @version    	1.0
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */

/** Momoger_Controller_Public */
//require_once 'Momoger/Controller/Public.php';

/**
 * 日志控制器.
 *
 * @category	Home
 * @package		Home_Controller
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */
class ArticleController extends Momoger_Controller_Public {

	/**
	 * 控制器初始化
	 *
	 * @return void
	 */
	public function mmInit() {
		$this->view->nav = 'article';
	}

	/**
	 * 默认显示网站日志页面
	 *
	 * @return HTML
	 */
	public function indexAction() {
		//$this->logger->debug('start action');
		//
		//Zend_Debug::dump($this->getRequest()->getParams());
		echo '<h1>Comming soon ...</h1>';
	}

	/**
	 * 添加新日志页面
	 *
	 * @return HTML
	 */
	public function addAction() {

		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        //auth use id
        if (!$this->user->userID) {
        	echo '<h1>You can not add new article! Please login first!</h1>';
        	exit();
        }

        $articleID = (int)$this->getRequest()->getParam('article_id', 0);

        $nowArticle = array();

        if ($articleID) {
        	$article = new Momoger_Model_Article();
        	$nowArticle = $article->getArticle($articleID, TRUE, TRUE, TRUE);
        }

        $category = new Momoger_Model_Category();
        $nowArticle['categories'] = $category->getCategories($this->user->userID, 'article');

		$this->view->user = $this->user;
		$this->view->articleID = $articleID;
		$this->view->article = $nowArticle;
	}

	public function addedAction() {
		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        $jsonRs = array('result' => false, 'msg' => 'You need login system!');

		//user id
		$userID = (int)$this->user->userID;

        //auth use id
        if (!$userID) {
        	$this->getHelper('Json')->sendJson($jsonRs);
        	return FALSE;
        }

        //get the article id, if set.
        $articleID = (int)$this->getRequest()->getParam('article_id');

        //build input filter object
        $filter = new Zend_Filter_StripTags();

        //get and filter the article title
        $articleTitle = $filter->filter($this->getRequest()->getParam('article_title'));

        //get and filter the article tags
        $tag = $filter->filter($this->getRequest()->getParam('article_tag'));
        if ($tag) {
        	$tag = explode(',', $tag);
        }

        //build input validate object and validate the article title content
        $validator = new Zend_Validate_StringLength(2, 250);
        if (!$validator->isValid($articleTitle)) {
        	$jsonRs['msg'] = 'Article title length must be in 2 - 250 charactors!';
        	$this->getHelper('Json')->sendJson($jsonRs);
        	return FALSE;
        }

        //get the article content
        $articleContent = $this->getRequest()->getParam('article_content');

        //modify filter let allow keep tag <img/> down.
        $filter->setTagsAllowed('<img>');

        //create the article preface content
        $articlePreface = $filter->filter($articleContent);

        //validate the article content
        $validator->setMin(4)->setMax(null);
        if (!$validator->isValid($articlePreface)) {
        	$jsonRs['msg'] = 'Article content too few!';
        	$this->getHelper('Json')->sendJson($jsonRs);
        	return FALSE;
        }

        //substr the article content for preface
        $articlePreface = App_Util_String::substr($articlePreface, 400);

        //strip article preface halfway img tags
		App_Util_String::stripHalfwayImgTag($articlePreface);

		//build category validator
		$validator = new Zend_Validate_Regex("/^[0-9]+(,[0-9]+)*$/");

		//get the article category information
		$category = $this->getRequest()->getParam('article_category');

		//validate the article category data
		if (!$validator->isValid($category)) {
			$jsonRs['msg'] = 'You need choose a category for this article at least!';
        	$this->getHelper('Json')->sendJson($jsonRs);
        	return FALSE;
		}
		$category = explode(',', $category);

		//create the article boject
        $modelArticle = new Momoger_Model_Article();

        $archiveID = 0;

        $isEditOption = false;

        //save article
        if ($articleID) {
        	$article = $modelArticle->getArticle($articleID);
        	if (!isset($article['userID']) || $userID != $article['userID']) {
        		$jsonRs['msg'] = 'You can not allow edit the article!';
        		$this->getHelper('Json')->sendJson($jsonRs);
        		return FALSE;
        	}
        	$isEditOption = true;
        	$archiveID = $modelArticle->get('archiveID');
        	$articleVersion = $modelArticle->get('articleVersion') + 1;
        	$modelArticle->set('articleUpdated', time());
        } else {
        	$articleVersion = 1;
	        $modelArticle->set('userID', $userID);

        }

        $modelArchive = new Momoger_Model_Archive();
        if (!$archiveID) {
        	$archive = $modelArchive->getNowArchive($userID, 'article');
        	$archiveID = $archive['archiveID'];
        }
        $modelArticle->set('archiveID', $archiveID);
        $modelArticle->set('articleTitle', $articleTitle);
        $modelArticle->set('articleVersion', $articleVersion);
        $modelArticle->set('articlePreface', $articlePreface);

        $modelArticle->save();

        //validate the save result
        $articleID = (int)$modelArticle->get('articleID');
        if (!$articleID) {
        	$jsonRs['msg'] = 'Sorry! The article save to database false!';
        	$this->getHelper('Json')->sendJson($jsonRs);
        	return FALSE;
        }

        //save the article tags
        $modelArticle->saveArticleTags($articleID, $tag);

        //save the article content
        $modelArticle->saveArticleCategories($articleID, $category);

        //save the article categories
        $modelArticle->articleContent()->set(array(
        	'articleID' => $articleID,
        	'articleVersion' => $articleVersion,
        	'articleContent' => $articleContent
        ))->insert();

        if (!$isEditOption) {
        	//update user article counts
			$modelUser = new Momoger_Model_User();
	        $modelUser->find($userID);
	        $modelUser->set('userArticles', $modelUser->get('userArticles') + 1);
	        $modelUser->update();
	        $this->user->userArticles += 1;

	        //update archive article counts
	        $modelArchive->find($archiveID);
	        $modelArchive->set('archiveCounts', $modelArchive->get('archiveCounts') + 1);
	        $modelArchive->save();

	        //update system status information
	        $modelProfile = new Momoger_Model_Profile();
	        $modelProfile->find(Momoger_Model_Profile::TOTAL_ARTICLE_NUMBER);
	        $modelProfile->set('pValue', $modelProfile->get('pValue') + 1);
	        $modelProfile->save();
        }

        $jsonRs['result'] = TRUE;
        $jsonRs['msg'] = 'Article Save Success!';
        $jsonRs['articleID'] = $articleID;
		$jsonRs['version'] = $articleVersion;

        $this->getHelper('Json')->sendJson($jsonRs);
        return TRUE;
	}

	/**
	 * 保存日志草稿数据
	 *
	 * @return HTML
	 */
	public function roughAction() {

		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

        //diable view helper
        //$this->getHelper('ViewRenderer')->setNoRender();

        $jsonRs = array('result' => false, 'msg' => 'User identify error!');

        //user id
		$userID = (int)$this->user->userID;

        //auth use id
        if (!$userID) {
        	$this->getHelper('Json')->sendJson($jsonRs);
        	return FALSE;
        }

        //save article rough data
        $content = $this->getRequest()->getParam('content');
        if ($content) {
        	$articleRough = new Momoger_Model_ArticleRough();
        	$articleRough->set(array('userID' => $userID, 'content' => $content))->save();
        }

        //end
        $jsonRs['result'] = TRUE;
        $jsonRs['msg'] = date('H:i:s');
        $this->getHelper('Json')->sendJson($jsonRs);
        return TRUE;
	}

	/**
	 * 添加新日志页面
	 *
	 * @return HTML
	 */
	public function listAction() {

		// close layout
		if (null !== ($layout = Zend_Layout::getMvcInstance())) {
            $layout->disableLayout();
        }

		//$this->logger->debug('start action');
		//
		//Zend_Debug::dump($this->getRequest()->getParams());
		echo '<h1>Comming soon ...</h1>';
	}
}